package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyComment;
import cn.wolfcode.trip.base.domain.UserLike;
import cn.wolfcode.trip.base.mapper.StrategyCommentMapper;
import cn.wolfcode.trip.base.mapper.StrategyMapper;
import cn.wolfcode.trip.base.mapper.UserLikeMapper;
import cn.wolfcode.trip.base.mapper.UserLikeMapper;
import cn.wolfcode.trip.base.service.ICollectService;
import cn.wolfcode.trip.base.service.ILikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/11/16.
 */
@Service
public class LikeServiceImpl implements ILikeService {

    @Autowired
    private UserLikeMapper likeMapper;
    @Autowired
    private StrategyMapper strategyMapper;
    @Autowired
    private StrategyCommentMapper commentMapper;

    @Override
    public UserLike get(Long userId,Long likeId,Integer type) {
        return likeMapper.getlike(userId,likeId,type);
    }

    @Override
    public Integer save(UserLike ul) {
        likeMapper.insert(ul);
        if(ul.getType()==UserLike.TYPE_STRATEGY) {
            strategyMapper.addOneLike(ul.getLikeId());
            Integer likes = strategyMapper.selectByPrimaryKey(ul.getLikeId()).getLikes();
            return likes;
        }
        return ul.getType()+11;//

    }

    @Override
    public Integer delete(Long userId,Long likeId,Integer type) {
        if(type==UserLike.TYPE_STRATEGY){
            strategyMapper.delOneLike(likeId);
            likeMapper.deleteLike(userId,likeId,type);
            return strategyMapper.selectByPrimaryKey(likeId).getLikes();
        }
        likeMapper.deleteLike(userId,likeId,type);
        return type+12;//
    }

    @Override
    public List<UserLike> getUserLikeList(Long userId, Integer type) {
        return null;
    }

    @Override
    public Map updateCommnetLikes(UserLike userLike) {
        //查询该用户有没有点赞这条评论
        UserLike like = likeMapper.getlike(userLike.getUserId(), userLike.getLikeId(), userLike.getType());
        //查询到这条评论的点赞数
        StrategyComment strategyComment = commentMapper.selectByPrimaryKey(userLike.getLikeId());
        Integer likes = strategyComment.getLikes();
        HashMap<String, Object> map = new HashMap<>();
        if(like==null){//如果没有点赞
            likeMapper.insert(userLike);//添加一条点赞数据
            //查到该评论的点赞数，增加1然后返回
            commentMapper.updateLikes(strategyComment.getId(),likes+1);
            map.put("liked",1);//已经点赞
            map.put("likeNum",likes+1);//最新的点赞数
            //返回点赞数
        }else{//删除点赞数据
            likeMapper.deleteLike(userLike.getUserId(),userLike.getLikeId(),userLike.getType());
            commentMapper.updateLikes(strategyComment.getId(),likes-1);
            map.put("liked",0);//已经取消点赞
            map.put("likeNum",likes-1);//最新的点赞数
        }
        return map;
    }
}
